package com.service.component.common.utils;

import com.alibaba.fastjson.JSONObject;
import com.service.component.user.entity.Users;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.pdfbox.pdmodel.interactive.digitalsignature.PDSeedValueMDP;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.*;
import java.util.function.BiPredicate;

/**
 * @author ：Calvin
 * @date ：Created in 2021/7/16 14:35
 * @description：公共工具类
 * @modified By：
 * @version: 1.0.0$
 */
public class CommonUtils {

    public static final Integer SALT_DIGITS = 6;
    public static final Integer USER_NO_DIGITS = 6;


    /**
     * 判断对象或者map所有的属性是否为空
     *    为空返回true
     *    不为空返回false
     * @param obj 对象
     * @return true or false
     * @throws IllegalAccessException 异常
     */
    public static boolean isAllfiledNull(Object obj) throws IllegalAccessException {
        boolean flag = true;
        if (ObjectUtils.isEmpty(obj)) return flag;
        if (obj instanceof Map) {
            Map map = (Map) obj;
            for (Object key : map.keySet()) {
                if (ObjectUtils.isNotEmpty(map.get(key))) {
                    flag = false;
                    break;
                }
            }
        } else {
            Class<?> aClass = obj.getClass();
            Field[] fields = aClass.getFields();
            for (Field field : fields) {
                field.setAccessible(true);
                if (ObjectUtils.isNotEmpty(field.get(obj))) {
                    flag = false;
                    break;
                }
            }
        }
        return flag;
    }


    /**
     * 将object转成List<T>
     *
     * @param obj
     * @param tClass
     * @param <T>
     * @return
     */
    public static <T> List<T> caseList(Object obj, Class<T> tClass) {
        List<T> result = new ArrayList<T>();
        if (obj instanceof List<?>) {
            for (Object o : (List<?>) obj) {
                result.add(tClass.cast(o));
            }
            return result;
        }
        return null;
    }

    /**
     * 比对两个数据，返回不同或者相同的数据属性字段以及属性值
     *
     * @param obj1          对象1
     * @param obj2          对象2
     * @param ignoreFields  忽略的字段
     * @param isGetDiffData 是否获取不同属性
     * @return
     * @throws IllegalAccessException
     */
    public static Map<String, String> compareTwoObj(Object obj1, Object obj2, String[] ignoreFields, boolean isGetDiffData) throws IllegalAccessException {
        Map<String, String> diffMap = new LinkedHashMap<>();
        List<String> ignoreFieldList = ObjectUtils.isNotEmpty(ignoreFields) ? Arrays.asList(ignoreFields) : new ArrayList<>();
        Class<?> obj1Class = obj1.getClass();
        Class<?> obj2Class = obj2.getClass();
        Field[] obj1ClassDeclaredFields = obj1Class.getDeclaredFields();
        Field[] obj2ClassDeclaredFields = obj2Class.getDeclaredFields();
        BiPredicate biPredicate = new BiPredicate() {
            @Override
            public boolean test(Object object1, Object object2) {
                if (ObjectUtils.isEmpty(object1) && ObjectUtils.isEmpty(object2)) {
                    return true;
                }
                if (ObjectUtils.notEqual(object1, object2)) {
                    return false;
                }
                if (!ObjectUtils.notEqual(object1, object2)) {
                    return true;
                }
                //需要特殊处理的类型 如:
                if (object1 instanceof BigDecimal && object2 instanceof BigDecimal) {
                    if (ObjectUtils.isEmpty(object1) ^ ObjectUtils.isEmpty(object2)) {
                        return false;
                    }
                    return ((BigDecimal) object1).compareTo((BigDecimal) object2) == 0;
                }
                return false;
            }
        };
        for (Field field1 : obj1ClassDeclaredFields) {
            for (Field field2 : obj2ClassDeclaredFields) {
                if (ignoreFieldList.contains(field1) || ignoreFieldList.contains(field2)) {
                    continue;
                }
                if (StringUtils.equalsIgnoreCase(field1.getName(), field2.getName())) {
                    field1.setAccessible(true);
                    field2.setAccessible(true);
                    if (isGetDiffData ? !biPredicate.test(field1.get(obj1), field2.get(obj2)) : biPredicate.test(field1.get(obj1), field2.get(obj2))) {
                        String fieldName = field1.getName();
                        Object obj1Data = field1.get(obj1);
                        Object obj2Data = field2.get(obj2);
                        diffMap.put("`" + fieldName + "`属性:", "obj1Data:" + obj1Data + ",obj2Data:" + obj2Data + ";");
                    }
                }
            }
        }
        return diffMap;
    }

    /**
     * 随机生成N位的盐
     *
     * @param n 位数
     * @return 随机生成的盐
     */
    public static String getRandomSalt(int n) {
        char[] chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz01234567890!@#$%^&*()-+".toCharArray();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < n; i++) {
            char aChar = chars[new Random().nextInt(chars.length)];
            sb.append(aChar);
        }
        return sb.toString();
    }

    /**
     * java生成随机数字length位数
     *
     * @param length[生成随机数的长度]
     * @return 随机生成的用户编号
     */
    public static String getRandomNo(int length) {
        String val = "";
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            val += String.valueOf(random.nextInt(10));
        }
        return val;
    }

    public static <T> List<Map<String,Object>> listConvert(List<T> list){
        List<Map<String,Object>> list_map = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(list)) {
            list.forEach(item->{
                Map<String,Object> map = new HashMap<>();
            });
        }
        return list_map;
    }

    /**
     * 获取当前网络ip
     *
     * @return 返回IP
     */
    public static String getIpAddr() {
        HttpServletRequest request = getHttpServletRequest();
        String ipAddress = request.getHeader("x-forwarded-for");
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
            if (ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")) {
                //根据网卡取本机配置的IP
                InetAddress inet = null;
                try {
                    inet = InetAddress.getLocalHost();
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
                ipAddress = inet.getHostAddress();
            }
        }
        //对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
        if (ipAddress != null && ipAddress.length() > 15) { //"***.***.***.***".length() = 15
            if (ipAddress.indexOf(",") > 0) {
                ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
            }
        }
        return ipAddress;
    }

    /**
     * 将 map 数据封装成javaBean
     *
     * @param map   Map类型数据
     * @param clazz 需要转换的JavaBean
     * @param <T>   泛型
     * @return JavaBean
     */
    public static <T> T convert(Map<String, Object> map, Class<T> clazz) {
        if (map == null || clazz == null) {
            return null;
        }
        T result = null;
        try {
            result = clazz.newInstance();
            BeanUtils.populate(result, map);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 注入 HttpServletRequest
     *
     * @return HttpServletRequest
     */
    public static HttpServletRequest getHttpServletRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }

    /**
     * 注入 HttpServletResponse
     *
     * @return HttpServletResponse
     */
    public static HttpServletResponse getHttpServletResponse() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
    }

    /**
     * 注入 HttpSession
     *
     * @return HttpSession
     */
    public static HttpSession getHttpSession() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getSession();
    }

    public static void main(String[] args) {
        System.out.println(!StringUtils.endsWithIgnoreCase(null,""));
    }
}
